# -*- coding: UTF-8 -*-
from . import BaseController
from backend.libs import myjson as json
from backend.models import Advertisement


class AdvertisementListController(BaseController):

    def get(self):
        t = Advertisement.objects
        advert_name = self.get_argument('advertName', '')
        if advert_name:
            t = t.filter(name__contains=advert_name)

        state = self.int_argument('state', 0)
        t = t.filter(state=state).order_by('state', 'show_order')
        
        number_per_page = self.int_argument('pageSize', 100)
        paginator = self.pagination(t.all(), number_per_page=number_per_page)

        return self.render_json(data=paginator)


class CreateAdvertController(BaseController):

    def post(self):
        data = json.loads(self.request.body)
        if not data['name']:
            return self.render_json(code=1001, msg='标签名称不能为空')
        print(data)
        advert_id = data.get('id', -1)

        advert = Advertisement() if int(advert_id) <= 0 else Advertisement.objects.filter(id=advert_id).first()
        advert.name = data['name']
        advert.category_id = data.get('category_id', 1)
        advert.image_file = data['image_file']
        advert.url = data['url']
        advert.state = data['state']
        advert.show_order = data['show_order']
        advert.save()
        return self.render_json(data=advert.to_dict())


class DeleteAdvertController(BaseController):

    def post(self, advert_id):
        advert_id = int(advert_id)
        if advert_id > 0:
            advert = Advertisement.objects.filter(id=advert_id).first()
            if advert:
                advert.delete()

        return self.render_json()